<template>
  <el-form ref="ruleForm"
           :model="form"
           inline
           class="ConsigneeDurationSet">
    <p>送货时效设置</p>
    <div class="tips">
      本公司创建的订单送货时效遇周六、周日、法定节假日顺延至勾选日第二天（即该订单在勾选日第二天23点59分59秒前到达或签收，送货时效为达标）；法定节假日的优先级高于周六、周日。
    </div>
    <el-form-item>
      <div style="display: flex">
        <span style="margin-right: 10px">剔除</span>
        <el-checkbox-group v-model="checkoutList">
          <el-checkbox v-for="(item, index) in timeList"
                       :key="index"
                       :label="item.label"
                       border></el-checkbox>
        </el-checkbox-group>
      </div>
    </el-form-item>
    <el-form-item>
      <div class="holiday">
        <span>节假日：</span>
        <el-checkbox v-model="festival"
                     label="法定节日"
                     @change="changeFestival"></el-checkbox>
        <el-checkbox v-show="festival"
                     v-model="holiday"
                     label="假日"
                     @change="changeHoliday"></el-checkbox>
        <el-popover placement="bottom"
                    width="400"
                    trigger="hover">
          <div class="info-title">法定节假日说明：</div>
          <p>例如国庆节，国家规定10月1号、2号、3号为法定节日；10月4号、5号、6号、7号为假日</p>
          <ol class="info-style">
            <li>假日不能单独勾选，只能在法定节日勾选的情况下勾选</li>
            <li>节假日只勾选法定节日适用于部分收货方只休法定节日，假日为正常上班日</li>
          </ol>
          <div style="text-align: center">
            <img style="width: 300px"
                 src="../../../static/images/date.png" />
          </div>
          <div slot="reference">
            <span class="example">
              (示例)
              <i slot="reference"
                 class="iconcaozuoshuoming iconfont"
                 style="color: #ff6500"></i>
            </span>
          </div>
        </el-popover>
      </div>
    </el-form-item>
    <p style="margin-top: 35px">
      签收异常通知
      <i class="iconcaozuoshuoming iconfont"
         style="color: #ff6500"></i>
      <span v-if="!signExceptionWarnSwitch">&nbsp;&nbsp;未开通，请联系管理员开通！</span>
    </p>
    <div class="tips">
      订单扫码/收货方小程序签收异常时将语音通知到发货联系人电话上。
    </div>
    <el-form-item label="语音通知">
      <el-switch v-model="voiceSwitch"
                 :disabled="!signExceptionWarnSwitch" />
    </el-form-item>
    <div class="tips">订单扫码/收货方小程序签收异常时将短信通知到发货联系人电话上。</div>
    <el-form-item label="短信通知">
      <el-switch v-model="smsSwitch"
                 :disabled="!signExceptionWarnSwitch" />
    </el-form-item>
    <p style="margin-top: 35px">
      推送数字化电子回单
      <i class="iconcaozuoshuoming iconfont"
         style="color: #ff6500"></i>
      <span v-if="!switchFlag">&nbsp;&nbsp;未开通，请联系管理员开通！</span>
    </p>
    <div class="tips">收货人扫码签收,将生成的数字化回单推送至收货方邮箱。</div>
    <el-form-item label="推送">
      <el-switch v-model="certPushSwitch"
                 :disabled="!certPushSwitchDisabled" />
    </el-form-item>
    <div v-if="emailInputShow">
      <el-form-item prop="contactEmail"
                    label="邮箱"
                    :rules="[
                {
                  required: false,
                  message: `请输入正确的邮箱`,
                  validator: validateEmail,
                  trigger: 'change'
                }
              ]">
        <el-input v-model="form.contactEmail"
                  placeholder="请输入收货方邮箱地址" />
      </el-form-item>
      <span class="tips_sty">说明：保存后，发送验证链接至邮箱。</span>
    </div>
    <div v-if="emailLabelShow">
      <el-form-item label="邮箱">
        {{form.contactEmail}}
        <el-button type="text"
                   @click="changeEmaill">修改</el-button>
      </el-form-item>
      <div>收货方邮箱验证状态：{{emailStatusName}}</div>
    </div>
    <el-button type="primary"
               class="btn-primary"
               size="medium"
               :loading="loading"
               @click="handleSubmit">保存</el-button>
  </el-form>
</template>

<script>
import { consignee } from "@/api/index.js";
import _ from "lodash";
let reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
export default {
  name: 'SetConsignee',
  props: {
    value: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      timeList: [
        { label: "周六" },
        { label: "周日" }
      ],
      checkoutList: [],
      festival: false,
      holiday: false,
      time: [],
      loading: false,
      smsSwitch: false,
      voiceSwitch: false,
      signExceptionWarnSwitch: false,
      certPushSwitch: false,
      certPushSwitchDisabled: false,
      changeFlag: false,
      switchFlag: false,
      form: {
        contactEmail: null
      }
    };
  },
  computed: {
    config () {
      return this.value.config
    },
    emailStatus () {
      return this.value?.emailStatus || 0
    },
    emailStatusName () {
      return this.value?.emailStatusName
    },
    emailInputShow () {
      return this.switchFlag && (this.emailStatus === 0 || this.changeFlag)
    },
    emailLabelShow () {
      return this.switchFlag && this.emailStatus !== 0 && !this.changeFlag
    }
  },
  created () {
    this.getConfig();
    if (this.config) {
      this.smsSwitch = this.config.smsSwitch;
      this.voiceSwitch = this.config.voiceSwitch;
      this.certPushSwitch = this.config.certPushSwitch;
      if (this.config.deliveryTime && this.config.deliveryTime.length > 0) {
        this.config.deliveryTime.map((item) => {
          if (item === 6) this.checkoutList.push("周六");
          if (item === 0) this.checkoutList.push("周日");
          if (item === 1) {
            this.festival = true
            this.time.push(1)
          }
          if (item === 2) {
            this.holiday = true
            this.time.push(2)
          }
        });
      }
    }
  },
  methods: {
    validateEmail (rule, value, callback) {
      if (value) {
        if (reg.test(value)) {
          callback();
        } else {
          callback(
            new Error("请输入正确的邮箱")
          );
        }
      }
    },
    changeEmaill () {
      this.changeFlag = true;
    },
    async getConfig () {
      let { code, data } = await consignee.searchTenant()
      if (code === 0 && data) {
        this.form.contactEmail = this.value?.contactEmail;
        this.signExceptionWarnSwitch = data.config?.signExceptionWarnSwitch
        this.switchFlag = data.config?.certSwitch && data.config?.certPushSwitch
        // 开通数字化回单，且开通推送服务，且邮箱验证成功
        this.certPushSwitchDisabled = this.switchFlag && this.certPushSwitch && this.emailStatus === 1;
      }
    },
    handleSubmit: _.debounce(function () {    // 触发事件
      if (this.form.contactEmail) {
        let flag = reg.test(this.form.contactEmail)
        if (!flag) return flag;
      }
      this.$confirm("将按页面内容进行保存，确定保存吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.save();
        this.loading = true;
      });
    }, 600),
    async save () {
      let deliveryTimeValue = [];
      this.checkoutList.map((item) => {
        if (item === "周日") deliveryTimeValue.push(0);
        if (item === "周六") deliveryTimeValue.push(6);
      });
      let sendConfirmEmail =
        this.switchFlag
          && this.form.contactEmail
          && (this.emailStatus === 0 || this.emailStatus === 4 || (this.changeFlag && (this.form.contactEmail != this.value.contactEmail)))
          ? 1
          : 0;

      let { message, code } = await consignee.getConsigneeReceiving({
        consigneeId: this.value.consigneeId,
        smsSwitch: this.smsSwitch,
        voiceSwitch: this.voiceSwitch,
        certPushSwitch: this.certPushSwitch,
        contactEmail: !this.certPushSwitch && this.emailStatus === 1 ? null : this.form.contactEmail,
        sendConfirmEmail,
        deliveryTime: [...deliveryTimeValue, ...this.time]
      }).catch(() => {
        this.loading = false;
      })
      if (code === 0) {
        this.loading = false;
        this.$message.success(message)
        this.$emit("confirm");
      }
    },
    changeFestival () {
      if (this.festival) {
        this.time.push(1)
      } else {
        this.time.pop()
        this.time.pop()
        this.holiday = false
      }
    },
    changeHoliday () {
      if (this.holiday) {
        this.time.push(2)
      } else {
        this.time.pop()
      }
    }
  }
}
</script>

<style scoped>
.ConsigneeDurationSet {
  padding: 20px;
}
.tips {
  background: #eeeeee;
  padding: 10px;
  margin: 10px 0 20px;
  border-radius: 5px;
  line-height: 20px;
  font-size: 14px;
}
.btn-primary {
  display: block;
  margin: 15px 0;
}
.holiday {
  display: flex;
  padding: 0 20px;
  border: 1px solid var(--prev-border-color-grey);
  line-height: 30px;
}
.holiday >>> .el-checkbox-group {
  display: flex;
  margin-right: 60px;
}
.holiday >>> .el-checkbox {
  margin-right: 8px;
}
.example {
  color: rgba(12, 128, 206);
  margin-left: 20px;
  cursor: pointer;
}
.el-checkbox-group >>> .el-checkbox.is-bordered.el-checkbox--small {
  padding: 5px 10px;
  margin-right: 5px;
}
.tips_sty {
  line-height: 30px;
}
</style>